#pragma once
#include <iostream>
#include <cstring>

#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <functional>

static const std::string defaultip = "0.0.0.0";
static const int gnum = 1024;

typedef std::function<void(int, std::string, uint16_t, std::string)> func_t;

enum Err
{
    USAGE_ERR = 1,
    SOCKET_ERR,
    BIND_ERR,
    OPEN_ERR
};

class Server
{
public:
    Server(const func_t &callback, const uint16_t &port, const std::string &ip = defaultip)
        : _callback(callback), _port(port), _ip(ip), _sockfd(-1) {}

    void initServer()
    {
        // 创建一个socket
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd == -1)
        {
            std::cerr << "socket error" << errno << ":" << strerror(errno) << std::endl;
            exit(SOCKET_ERR);
        }
        // 将对应的ip和port设置进socket
        struct sockaddr_in local;
        bzero(&local, sizeof(local)); // 清空local中的内容
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        // local.sin_addr.s_addr = inet_addr(_ip.c_str());
        local.sin_addr.s_addr = htonl(INADDR_ANY);
        // 将socket和本地地址进行绑定进行绑定
        int n = bind(_sockfd, (struct sockaddr *)&local, sizeof(local));
        if (n == -1)
        {
            std::cerr << "bind error" << errno << ":" << strerror(errno) << std::endl;
            exit(BIND_ERR);
        }
    }

    void start()
    {
        char buffer[gnum];
        while (true)
        {
            struct sockaddr_in peer; // 用来存储发送端的ip和端口号
            socklen_t len = sizeof(peer);
            ssize_t s = recvfrom(_sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&peer, &len);

            if (s > 0)
            {
                buffer[s] = 0;
                std::string clientip = inet_ntoa(peer.sin_addr);//将网络序列转为主机序列，并将int型的port转为点分十进制类型
                uint16_t clientport = ntohs(peer.sin_port);//将网络序列转成主机序列
                std::string message = buffer;

                std::cout << clientip << "[" << clientport << "]# " << message << std::endl;

                _callback(_sockfd, clientip, clientport, message);
            }
        }
    }

    ~Server() {}

private:
    uint16_t _port;
    std::string _ip;
    int _sockfd;
    func_t _callback; // 回调
};